package com.rengwuxian.wecompose.ui

import android.content.Intent
import android.widget.Toast
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.ConstraintSet
import cn.hutool.core.util.ReUtil
import cn.hutool.http.HttpRequest
import cn.hutool.json.JSONUtil
import com.jiayou.SimpleAuthPackPackageImpl
import com.rengwuxian.wecompose.activity.MainActivity
import com.rengwuxian.wecompose.activity.MainActivity.Companion.context
import com.rengwuxian.wecompose.activity.MainActivity.Companion.uri
import com.rengwuxian.wecompose.activity.R
import com.rengwuxian.wecompose.activity.RegisterActivity
import com.rengwuxian.wecompose.data.User
import com.rengwuxian.wecompose.mv.IndexViewModel
import com.rengwuxian.wecompose.ui.theme.WeTheme
import kotlinx.coroutines.*
import kotlin.concurrent.thread

/**
@author lishuang
@data   2021-11-13  15:36
@info
 */


@Composable
@ExperimentalComposeUiApi
@ExperimentalAnimationApi
fun Index(indexViewModel: IndexViewModel) {
    val context = LocalContext.current
    MaterialTheme {
        val decoupledConstraints = decoupledConstraints()
        ConstraintLayout(
            decoupledConstraints, modifier = Modifier
                .fillMaxHeight(1.0F)
                .fillMaxWidth(1.0F)
                .border(BorderStroke(5.dp, Color.Blue))
        ) {
            Title(indexViewModel)
            Input(indexViewModel)
            Login(indexViewModel)
            Bottom(indexViewModel)
        }
    }

}


@ExperimentalAnimationApi
@Composable
fun Title(model: IndexViewModel) {
    thread {
        Thread.sleep(500)
        model.title = true
    }
    AnimatedVisibility(
        visible = model.title,
        enter = slideInHorizontally(),
        exit = slideOutHorizontally(),
        modifier = Modifier.layoutId("title")
    ) {
        Row(
            modifier = Modifier
                .width(300.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Image(
                painter = painterResource(id = R.drawable.im), contentDescription = "图片",
                Modifier
                    .padding(12.dp, 8.dp, 12.dp, 8.dp)
                    .size(60.dp)
            )
            Text(text = "Wecompose-net")
        }
    }
}

@Composable
@ExperimentalAnimationApi
fun Input(model: IndexViewModel) {
    val current = LocalContext.current
    thread {
        Thread.sleep(1100)
        model.input = true
    }
    AnimatedVisibility(
        visible = model.input,
        enter = slideInHorizontally(),
        exit = slideOutHorizontally(),
        modifier = Modifier.layoutId("input")
    ) {
        Column(horizontalAlignment = Alignment.CenterHorizontally) {
            Row(
                Modifier
                    .fillMaxWidth(0.9f)
                    .height(1.dp)
            ) {
                Divider(color = WeTheme.colors.chatListDivider, thickness = 0.8f.dp)
            }
            OutlinedTextField(
                value = model.username,
                onValueChange = {
                    if (it.isEmpty()) {
                        model.username = ""
                    } else if (it.length <= 16)
                        if (ReUtil.isMatch("[0-9|a-z|]*", it))
                            model.username = it
                },
                Modifier
                    .fillMaxWidth(0.8f)
                    .height(60.dp)
                    .clip(MaterialTheme.shapes.small),
                label = { Text(text = "用户名", fontSize = 13.sp) },
                placeholder = { Text(text = "请输入用户名", fontSize = 11.sp) },
                leadingIcon = {
                    Image(
                        painter = painterResource(id = R.drawable.username), contentDescription = "用户名",
                        Modifier.size(15.dp)
                    )
                },
                colors = TextFieldDefaults.textFieldColors(
                    focusedIndicatorColor = Color.Transparent, // 有焦点时的颜色，透明
                    unfocusedIndicatorColor = Color.Transparent, // 无焦点时的颜色，绿色
                    errorIndicatorColor = Color.Red, // 错误时的颜色，红色
                    disabledIndicatorColor = Color.Gray // 不可用时的颜色，灰色
                ),
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
                singleLine = true
            )
            Row(
                Modifier
                    .fillMaxWidth(0.9f)
                    .height(1.dp)
            ) {
                Divider(color = WeTheme.colors.chatListDivider, thickness = 0.8f.dp)
            }
            OutlinedTextField(
                value = model.password,
                onValueChange = {
                    if (it.isEmpty()) {
                        model.password = ""
                    } else if (it.length <= 16) {
                        if (ReUtil.isMatch("[0-9|a-z|\\.]*", model.password + it.last())) {
                            model.password = it
                        }
                    }
                },
                Modifier
                    .fillMaxWidth(0.8f)
                    .height(60.dp)
                    .clip(MaterialTheme.shapes.small),
                label = { Text(text = "密码", fontSize = 13.sp) },
                placeholder = { Text(text = "请输入密码", fontSize = 11.sp) },
                leadingIcon = {
                    Image(
                        painter = painterResource(id = R.drawable.username), contentDescription = "密码",
                        Modifier.size(15.dp)
                    )
                },
                colors = TextFieldDefaults.textFieldColors(
                    focusedIndicatorColor = Color.Transparent, // 有焦点时的颜色，透明
                    unfocusedIndicatorColor = Color.Transparent, // 无焦点时的颜色，绿色
                    errorIndicatorColor = Color.Red, // 错误时的颜色，红色
                    disabledIndicatorColor = Color.Gray // 不可用时的颜色，灰色
                ),
                visualTransformation = PasswordVisualTransformation(),
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
                singleLine = true
            )
            Row(
                Modifier
                    .fillMaxWidth(0.9f)
                    .height(1.dp)
            ) {
                Divider(color = WeTheme.colors.chatListDivider, thickness = 0.8f.dp)
            }
        }
    }
}

@Composable
@ExperimentalAnimationApi
fun Login(model: IndexViewModel) {
    val current = LocalContext.current
    thread {
        Thread.sleep(1300)
        model.login = true
    }

    AnimatedVisibility(
        visible = model.login,
        enter = slideInHorizontally(),
        exit = slideOutHorizontally(),
        modifier = Modifier.layoutId("login")
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            IconButton(onClick = {
                thread {
                    runBlocking {
                        val parse = JSONUtil.parseObj(
                            HttpRequest
                                .get("http://$uri/im/user/login")
                                .form(mapOf("username" to model.username, "password" to model.password))
                                .header("auth", "73913da7-508b-4646-b8ae-ef6458f41153")
                                .execute()
                                .body().also { println(it) }
                        )
                        println(parse)
                        withContext(Dispatchers.Main) {
                            Toast.makeText(current, parse["message"].toString(), Toast.LENGTH_SHORT).show()
                        }
                        if (parse["code"].toString().toInt() == 200) {
                            MainActivity.userInfo = JSONUtil.parseObj(parse["data"]).toMap() as HashMap<String, Any>
//                            println(MainActivity.userInfo)
                            User.Me =
                                User(
                                    MainActivity.userInfo["username"].toString(),
                                    MainActivity.userInfo["petname"].toString(),
                                    R.drawable.avatar_rengwuxian
                                )
                            model.logined = true

                            withContext(Dispatchers.IO) {
                                MainActivity.client.clientSocketSession.authenticatePackage =
                                    SimpleAuthPackPackageImpl(model.username, model.password)
                                MainActivity.client.start()
                            }

                        }
                    }
                }
            }) {
                Image(
                    painter = painterResource(id = R.drawable.login), contentDescription = "登录"
                )
            }
        }
    }
}

@Composable
@ExperimentalAnimationApi
fun Bottom(model: IndexViewModel) {

    var visible by remember { mutableStateOf(model.login) }
    thread {
        Thread.sleep(1500)
        visible = true
    }
    AnimatedVisibility(
        visible = visible,
        enter = slideInHorizontally(),
        exit = slideOutHorizontally(),
        modifier = Modifier.layoutId("bottom")
    ) {
        Row(
            Modifier.height(40.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            TextButton(onClick = { /*TODO*/ }, modifier = Modifier.fillMaxHeight()) {
                Text(text = "手机号登录", color = Color.Black, fontSize = 11.sp, fontWeight = FontWeight.W600)
            }
            Row(
                modifier = Modifier
                    .padding(18.dp, 0.dp)
                    .fillMaxHeight(0.3f)
                    .width(1.dp)
                    .background(WeTheme.colors.chatListDivider),
            ) {

            }
            TextButton(onClick = { /*TODO*/ }) {
                Text(text = "找回密码", color = Color.Black, fontSize = 11.sp, fontWeight = FontWeight.W600)
            }
            Row(
                modifier = Modifier
                    .padding(18.dp, 0.dp)
                    .fillMaxHeight(0.3f)
                    .width(1.dp)
                    .background(WeTheme.colors.chatListDivider),
            ) {

            }
            TextButton(onClick = {
                context.startActivity(Intent(context, RegisterActivity::class.java))
            }) {
                Text(text = "新用户注册", color = Color.Black, fontSize = 11.sp, fontWeight = FontWeight.W600)
            }
        }
    }
}


private fun decoupledConstraints(): ConstraintSet {
    return ConstraintSet {
        val title = createRefFor("title")
        val input = createRefFor("input")
        val login = createRefFor("login")
        val bottom = createRefFor("bottom")
        constrain(title) {
            top.linkTo(parent.top, 100.dp)
            start.linkTo(parent.start, 70.dp)
        }
        constrain(input) {
            top.linkTo(title.bottom, 50.dp)
            start.linkTo(parent.start)
            end.linkTo(parent.end)
        }
        constrain(login) {
            top.linkTo(input.bottom, 50.dp)
            start.linkTo(parent.start)
            end.linkTo(parent.end)
        }
        constrain(bottom) {
            start.linkTo(parent.start)
            this.bottom.linkTo(parent.bottom, 20.dp)
            start.linkTo(parent.start)
            end.linkTo(parent.end)
        }
    }
}